// src/router/guards.js
import axios from 'axios';
import { getActivePinia } from 'pinia';

// 异步检查用户登录状态
const checkIsLogged = async () => {
    try {
        const response = await axios.get("/user/isLogged");
        const user = response.data;
        console.log('user-regulate data:', user);
        // 动态导入 store 并更新 Pinia 中用户信息
        const { userStore } = await import('../store/index.js');
        const userItemStore = userStore();
        userItemStore.updateUser(user);
        userItemStore.updateLoginStatus(true);
        return true;
    } catch (error) {
        console.error('Error checking login status:', error);
        // 动态导入 store 并更新 Pinia 中用户信息
        const { userStore } = await import('../store/index.js');
        const userItemStore = userStore();
        userItemStore.updateUser({});
        userItemStore.updateLoginStatus(false);
        console.log('user-regulate not logged in.');
        return false;
    }
};

// 设置全局前置守卫
export const setupGuards = (router) => {
    console.log('Setting up guards. Checking if Pinia is active:', getActivePinia());

    router.beforeEach(async (to, from, next) => {
        console.log('Navigating to:', to.path);
        const isLogin = await checkIsLogged();
        const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
        console.log('Requires auth:', requiresAuth, 'Is logged in:', isLogin);

        if (requiresAuth && !isLogin) {
            console.log('Redirecting to login page.');
            next('/login'); // 如果目标路由需要认证且用户未登录，则重定向到登录页面
        } else if (!requiresAuth && isLogin && to.path === '/login') {
            console.log('Redirecting to user-regulate page.');
            next('/'); // 如果用户已登录但尝试访问登录页面，则重定向到主页或其他指定页面
        } else {
            console.log('Proceeding with navigation.');
            next(); // 否则继续导航
        }
    });
};